<script setup>
import { ElMessage } from 'element-plus'
import {computed, ref, onMounted, reactive} from "vue";
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import axios from "axios"
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
//添加点击事件  点击完后 进行判断  如果密码和用户吻合 , 那就直接走router跳转并传值
let username = ref("张三");
let password = ref("123");

const itemLabelPosition = ref('right');

//注册弹窗是否开启
const dialogFormVisible = ref(false);
const store = useStore();

const router = useRouter();

let useryanzhengma = ref("");
const userArr = computed(()=>{
  return store.state.userList;
})

const massagePage = reactive({
  consultantName: "",
  fullName:"",
  consultantPassword:"",
  configPassword:"",
  consultantPhone: "",
  AddressSheng: "",
  AddressShi: "",
  consultantDesc: "",
  consultantIntroduction:"",
  consultantGender: 0,
  consultantAge: 1,
});
//登录按钮
const sumbit = function () {
  console.log(yanzhengma.value);
if (yanzhengma.value === useryanzhengma.value){
  axios.get("/consultants/login",{
    params:{
      name: username.value,
      password: password.value
    }})
      .then(res=>{
        console.log(res.data);
        if (res.data.code === 200){
          console.log(res.data.data.consultant);
          //跳转页面
          router.push("/home");
          //弹框提示
          open2("登录成功");
          // 保存数据到 sessionStorage
          const consultant = res.data.data.consultant;
          sessionStorage.setItem('user', JSON.stringify(consultant));
          sessionStorage.setItem('consultantId', consultant.consultantId);
          sessionStorage.setItem('token', JSON.stringify(res.data.data.token));
          store.state.user = JSON.parse(sessionStorage.getItem('user'));
        }else{
          open4(res.data.msg);
        }
      }).catch((error)=>{
    console.log(error);
  })
}else{
  open4("验证码错误");
}


}

//初始乱码
let ma = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";

let yanzhengma = ref("点击显示");

//随机验证码
const luanma = function() {
  let suijima = ref("");
  //循环四次
  for (let i = 0; i < 4; i++) {
    //每次随机取一个字母或数字
    // randomNumber(0, ma.length - 1);
    let charAtIndex = ma.charAt(randomNumber(0, ma.length - 1));
    suijima.value += charAtIndex;
  }
  console.log(suijima);
  return suijima.value;
}

//封装随机数
function randomNumber(min, max) {
  //Math.floor() 向下取整
  let num = Math.floor(Math.random() * (max - min + 1) + min);
  return num;
}

//登陆成功
const open2 = (msg) => {
  ElMessage({
    message: msg,
    type: 'success',
  })
}
//登陆失败
const open4 = (msg) => {
  ElMessage.error(msg);
}

//传入一个对象, 如果有这个对象中至少存在一个空字符串,那么就返回true
const hasEmptyString = function (obj) {
  return Object.values(obj).some(value => value === '');
}
//进入注册页面
const userRegister = function () {
  //开启弹窗
  dialogFormVisible.value = true;
  //初始化
  massagePage.consultantName = "";
  massagePage.AddressSheng = "";
  massagePage.consultantPhone = "";
  massagePage.AddressShi = "";
  massagePage.consultantDesc = "";
  massagePage.consultantIntroduction = "";
  massagePage.consultantGender = 0;
  massagePage.consultantAge = 1;
}
//确认注册
const register = function () {
  //判断是否有空字符串
  if (hasEmptyString(massagePage)) {
    open2("输入框中不能为空");
  }else{
    if(massagePage.configPassword === massagePage.consultantPassword){
      axios.post("/consultants/register", {
        consultantName: massagePage.consultantName,
        fullName: massagePage.consultantName,
        consultantPhone: massagePage.consultantPhone,
        consultantPassword: massagePage.consultantPassword,
        consultantGender: formatGenderValue(massagePage.consultantGender),
        consultantAge: massagePage.consultantAge,
        consultantDesc: massagePage.consultantDesc,
        consultantIntroduction: massagePage.consultantIntroduction,
        consultantAddress: massagePage.AddressSheng + massagePage.AddressShi,
      }).then((req)=>{
        if (req.data.code === 200){
          open2("注册成功");
          dialogFormVisible.value = false;
          //清空数据
          massagePage.consultantName = "";
          massagePage.consultantPhone = "";
          massagePage.consultantPassword = "";
          massagePage.configPassword = "";
          massagePage.AddressSheng = "";
          massagePage.AddressShi = "";
          massagePage.consultantDesc = "";
          massagePage.consultantIntroduction = "";
          massagePage.consultantGender = 0;
          massagePage.consultantAge = 1;
        }else{
          open4(req.data.msg);
        }
      }).catch((error)=>{
        console.error(error);
      })
    }else{
      open4("两次输入的密码不一致");
    }
  }
}
// 自定义格式化函数，将0或1转换为对应的字符串
const formatGenderValue = (value) => {
  return value === 0? '男' : '女';
};


// 获取所有的省份和城市数据
const provinces = computed(() => store.getters.getProvinceCityData);
const positions = ref([]); // 城市列表
// 当前选中的省份和城市
const selectedProvince = ref('');
const selectedCity = ref('');

// 根据选中的省份获取对应的城市列表
const fetchPositions = () => {
  massagePage.AddressShi = ''  //重置城市
  if (massagePage.AddressSheng) {
    positions.value = store.getters.getCitiesByProvince(massagePage.AddressSheng);
    return;
  }
  positions.value = [];
};



</script>

<template>

<div class="finalbox">
  <div>
    <img src="https://p8.itc.cn/q_70/images03/20210928/0ff4ac2dd2ab4f1299966aa7b4588f3d.jpeg" alt="">
  </div>
  <ul class="centerbox">
    <li>登录</li>
    <li>这个人很懒~什么都没写</li>
    <li><input class="admin" type="text" placeholder="请输入账号" v-model="username"  style="width: 194px;padding: 6px 12px" required></li>
    <li><input class="pword" type="password" placeholder="请输入密码" v-model="password"  style="width: 194px;padding: 6px 12px" required></li>

    <li class="yanzhengma">
      <input class="yanzheng" type="text" placeholder="验证码" v-model="useryanzhengma" style="width: 75px;padding: 6px 12px" required onkeyup="this.value=this.value.replace(/[^\w]/ig,'')">
      <div @click="yanzhengma=luanma()" style="width: 60px;padding: 6px 12px;margin-left: 20px;font-size: 14px;color: darkblue;background-color: whitesmoke">{{yanzhengma}}</div>

    </li>

    <li><input type="checkbox" name="rememberme" style="width: 16px;height: 16px;margin-top: 2px">
      <div>记住我</div>
    </li>
    <li>
      <el-button type="primary" @click="sumbit" style="width: 220px">登录</el-button>
    </li>
    <li>
      <!--      进入注册页面-->
      <el-button @click="userRegister" style="width: 220px">注册</el-button>
    </li>
    <li>
      <!--      注册页面 -->
      <el-dialog v-model="dialogFormVisible" title="添加员工" width="500" center>
        <el-form
            :label-position="labelPosition"
            label-width="auto"
            :model="massagePage"
            style="max-width: 600px"
        >

          <el-form-item label="用户名称" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.consultantName"/>
          </el-form-item>
          <el-form-item label="真实姓名" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.fullName"/>
          </el-form-item>

          <el-form-item label="用户密码" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.consultantPassword"/>
          </el-form-item>
          <el-form-item label="确认密码" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.configPassword"/>
          </el-form-item>

          <el-form-item label="手机号码" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.consultantPhone"/>
          </el-form-item>

          <!-- 添加控制性别的单选按钮部分 -->
          <el-form-item label="性别" :label-position="itemLabelPosition">
            <el-radio-group v-model="massagePage.consultantGender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="年龄" :label-position="itemLabelPosition">
            <el-input-number v-model="massagePage.consultantAge" :min="1" :max="150" :step="1"></el-input-number>
          </el-form-item>
          <!--            省市二级联动-->
          <el-form-item label="省份" :label-position="itemLabelPosition">
            <el-select v-model="massagePage.AddressSheng" placeholder="请选择省份"  @change="fetchPositions">
              <el-option style="color: #444444;"
                  v-for="(cities, province) in provinces"
                  :key="province"
                  :value="province"
                  :label="province"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="城市" :label-position="itemLabelPosition">
            <el-select v-model="massagePage.AddressShi" placeholder="请选择城市">
              <el-option style="color: #444444;"
                  v-for="city in positions"
                  :key="city"
                  :value="city"
                  :label="city"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="资质介绍" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.consultantDesc"/>
          </el-form-item>
          <el-form-item label="个人介绍" :label-position="itemLabelPosition">
            <el-input v-model="massagePage.consultantIntroduction"/>
          </el-form-item>
        </el-form>
        <div>
          <el-button style="margin-left: 70px" type="success" @click="register">确认注册</el-button>
          <el-button style="margin-left: 100px" type="danger" @click="router.push('/home/shouye')">返回登陆界面</el-button>
        </div>

      </el-dialog>


    </li>

  </ul>

</div>

</template>

<style scoped>
.finalbox{
  position: relative;
}
.finalbox div img{
  width: 100vw;
  height: 100vh;
}
.centerbox{
  width: 220px;
  padding: 30px;
  position: absolute;
  right: 400px;
  top: 200px;
  border-radius: 5px;
  background-color: rgba(0,0,0,.5);
}
ul li{
  margin-top: 15px;
  color: whitesmoke;
}
li:first-child{
  margin-top: 0;
  font-weight: 700;
}
li:nth-child(2){
  margin-top: 20px;
  font-size: 13px;
}
li:nth-child(6){
  display: flex;
  align-items: center;
  font-size: 13px;
  /*background-color: #FFB800;*/
}
li:nth-child(6) div{
  margin-left: 10px;
}
.yanzhengma{
display: flex;
}
.yanzhengma div{
  text-align: center;
}

</style>